import router from "../../router";
import store from "../index";
import {FindMenuList} from "../../api/menuApi";

const permission = {
    actions: {
        /**
         * 生成新路由表(前端生成)
         * @param commit
         */
        generateRoutes({commit}) {
            const route = router.options.routes;//获取路由表
            //循环遍历
            const newRoutes = [];
            for (let i = 0; i < route.length; i++) {
                //一级菜单中meta.role中是否包含当前登陆的角色
                const arr = route[i].meta.role.includes(store.getters.role);

                //如果包含
                if (arr) {
                    //如果存在子菜单
                    if (route[i].children !== undefined) {
                        //遍历子菜单
                        const newChildrenArray = [];
                        for (let c = 0; c < route[i].children.length; c++) {
                            //如果子菜单meta role中包含当前登陆的角色
                            if (route[i].children[c].meta.role.includes(store.getters.role)) {
                                newChildrenArray.push(route[i].children[c])
                            }
                        }

                        const routeJson = {
                            path: route[i].path,
                            component: route[i].component,
                            name: route[i].name,
                            iconCls: route[i].iconCls,
                            children: newChildrenArray
                        };
                        newRoutes.push(routeJson);
                    } else {
                        i++;
                    }
                }
                //如果不包含
                else {
                    i++
                }
            }
            commit('Set_Routes', newRoutes);
        },

        /**
         * 后台路由
         * @param commit
         * @returns {Promise<unknown>}
         */
        serverGenerateRoutes({commit}){
            return new Promise((resolve, reject) => {
                FindMenuList().then(res => {
                    commit('Set_Routes', res.data);
                    resolve();
                }).catch(err => {
                    reject(err);
                })
            })
        }

    },

}
export default permission